package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.USerDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.USerService;

import java.util.List;

public class UserServiceImpl implements USerService {

    private USerDao uSerDao;
    public void setuSerDao(USerDao uSerDao) {
        this.uSerDao = uSerDao;
    }

    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {
        List<User> list = uSerDao.findAll();
        //遍历list集合，获取每一个用户，封装roleList属性
        for (User user : list) {
            Long id = user.getId();
            List<Role> roles = roleDao.findRoleByUserId(id);
            user.setRoleList(roles);
        }
        return list;
    }

    public void save(User user, long[] roleIds) {
        //第一步：封装sys_user数据
        Long userId = uSerDao.save(user);
        //第二部：封装sys_user_role 数据
        uSerDao.saveUserRoleRel(userId,roleIds);
    }

    public void del(Long userId) {
        //第一步：根据userID删除sys_user_role中的数据
        uSerDao.delUserRoleRel(userId);

        //第一步：根据userID删除sys_user中的数据
        uSerDao.del(userId);
    }

    public User login(String username, String password) {
        User user = uSerDao.findByUsernameAndPassword(username,password);
        return user;
    }
}
